var resUrlPrefix = "/static/";
var version = "0.1.1";

function getFileDisplayName(fileName) {
    return fileName.replace(".json", "");
}

function buildZtreeData(treeData, parent) {
    var zNodes = [];

    var dirs = treeData.dirs;
    if (dirs) {
        dirs.forEach(dir => {
            var path = parent + "/" + dir.name;
            var children = buildZtreeData(dir, path);
            var child = { name: dir.name, open: true, children: children.children, iconOpen: resUrlPrefix + "/icon/down.svg?v=" + version, iconClose: resUrlPrefix + "/icon/right.svg?v=" + version, path: path };

            zNodes.push(child);
        });
    }

    var files = treeData.files;
    if (files) {
        files.forEach(file => {
            var path = parent + "/" + file;
            zNodes.push({ name: getFileDisplayName(file), icon: resUrlPrefix + "/icon/" + getIcon(file) + "?v=" + version, path: path })
        })
    }

    return { name: treeData.name, children: zNodes };
}

function showZtree(treeData, domId) {

    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
    var setting = { view: { showLine: false }, callback: { onClick: clickFileTree } };
    // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
    var zNodes = buildZtreeData(treeData, "").children;
    $(document).ready(function() {
        fileZtree = $.fn.zTree.init($("#" + domId), setting, zNodes);

        var level0 = $(".level0");
        $(level0[level0.length - 1]).click();
    });
}

function clickFileTree(event, treeId, treeNode) {

    if (treeNode.isParent) {
        fileZtree.expandNode(treeNode, !treeNode.open);
        return;
    }
    let title = getTabTitle(treeNode.path);
    var path = "/mini/dsl.html?code=/git/grammar-repo/aviatorscript/5/demo/" + treeNode.path + "&grammar=/git/grammar-repo/aviatorscript/5/DSL.g4&complete=/git/grammar-repo/aviatorscript/5/complete.js&monarch=/git/grammar-repo/aviatorscript/5/monarch.js&showTool=true&resultHeight=100&dsl=aviator";
    addTab(title, path);
}

function getTabTitle(path) {
    return path.replace(/^\//, "").replace(/\//g, ".");
}

function getIcon(file) {

    if (file.indexOf(".") > -1) {
        return file.substr(file.lastIndexOf(".") + 1, file.length) + ".svg";
    }

    return "default.svg";
}

$(function() {
    var menuUrl = "/git/grammar-repo/aviatorscript/5/menus.json";
    $.get(menuUrl, function(js) {
        var treeData = eval(js);
        treeData.files.sort();
        showZtree(treeData, "fileDir");
    })
});